package com.huixh.train.${packagePath}.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huixh.train.common.resp.PageResult;
import com.huixh.train.${packagePath}.domain.${Domain};
import com.huixh.train.${packagePath}.domain.${Domain}Example;
import com.huixh.train.${packagePath}.mapper.${Domain}Mapper;
import com.huixh.train.${packagePath}.req.${Domain}QueryReq;
import com.huixh.train.${packagePath}.req.${Domain}SaveReq;
import com.huixh.train.${packagePath}.resp.${Domain}QueryResp;
import com.huixh.train.${packagePath}.service.${Domain}Service;
import com.huixh.train.utils.random.SnowUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author huixh
*/
@Service
public class ${Domain}ServiceImpl implements ${Domain}Service {

    private final Logger logger = LoggerFactory.getLogger(${Domain}ServiceImpl.class);
    @Resource
    private ${Domain}Mapper ${domain}Mapper;

    @Resource
    private SnowUtil snowUtil;

    @Override
    public void save(${Domain}SaveReq ${domain}SaveReq) {
        DateTime now = DateTime.now();
        ${Domain} ${domain} = BeanUtil.copyProperties(${domain}SaveReq, ${Domain}.class);
        if (ObjectUtil.isNull(${domain}.getId())) {
            ${domain}.setId(snowUtil.getSnowflakeToLong());
            ${domain}.setCreateTime(now);
            ${domain}.setUpdateTime(now);
            ${domain}Mapper.insert(${domain});
        } else {
            ${domain}.setUpdateTime(now);
            ${domain}Mapper.updateByPrimaryKey(${domain});
        }
    }

    @Override
    public PageResult <List<${Domain}QueryResp>> queryList(${Domain}QueryReq ${domain}QueryReq) {
        ${Domain}Example ${domain}Example = new ${Domain}Example();
        ${domain}Example.setOrderByClause("id desc");
        ${Domain}Example.Criteria criteria = ${domain}Example.createCriteria();

        logger.info("查询页码：{}", ${domain}QueryReq.getPageNum());
        logger.info("每页条数：{}", ${domain}QueryReq.getPageSize());
        PageHelper.startPage(${domain}QueryReq.getPageNum(), ${domain}QueryReq.getPageSize());
        List<${Domain}> ${domain}List = ${domain}Mapper.selectByExample(${domain}Example);

        PageInfo<${Domain}> pageInfo = new PageInfo<>(${domain}List);
        logger.info("总行数：{}", pageInfo.getTotal());
        logger.info("总页数：{}", pageInfo.getPages());

        List<${Domain}QueryResp> list = BeanUtil.copyToList(${domain}List, ${Domain}QueryResp.class);
        return PageResult.success(pageInfo.getTotal(), list);
    }

    @Override
    public void delete(Long id) {
        ${domain}Mapper.deleteByPrimaryKey(id);
    }
}